package springboot;

import springboot.http.MyWebServer;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import java.util.Map;

/**
 * 自定义SpringBoot启动类
 */
public class MySpringApplication {
    public static void run(Class<?> clazz, String[] args) {
        //创建Spring容器
        AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
        //Spring容器注册配置类
        annotationConfigWebApplicationContext.register(clazz);
        //刷新Spring容器
        annotationConfigWebApplicationContext.refresh();
        //获取Web服务端
        MyWebServer myWebServer = getWebServer(annotationConfigWebApplicationContext);
        //启动Web服务端
        myWebServer.start(annotationConfigWebApplicationContext);
    }

    /**
     * 获取Web服务端
     */
    private static MyWebServer getWebServer(ApplicationContext applicationContext) {
        //根据类型从Spring容器获取Bean
        Map<String, MyWebServer> webServers = applicationContext.getBeansOfType(MyWebServer.class);
        if (webServers.isEmpty()) {
            throw new RuntimeException("未配置Web服务端");
        }

        if (webServers.size() > 1) {
            throw new RuntimeException("配置多个Web服务端");
        }

        return webServers.values().iterator().next();
    }
}